import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_application_1/components/city_list_selector/city_list_selector.dart';
import 'package:flutter_application_1/provider/location_provider.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:provider/provider.dart';

class SelectLocationSearchRow extends StatefulWidget {
  final Color primaryColor;
  final Function(String) onChanged;

  SelectLocationSearchRow({
    required this.primaryColor,
    required this.onChanged,
  });

  @override
  State<StatefulWidget> createState() => SelectLocationSearchRowState();
}

class SelectLocationSearchRowState extends State<SelectLocationSearchRow> {
  FocusNode focusNode = FocusNode();

  bool _hasFocus = false;

  late StreamSubscription keyboardListener;

  String _keyword = '';

  // 取消焦点
  void loseFocus() {
    FocusScope.of(context).requestFocus(FocusNode());
  }

  @override
  void initState() {
    super.initState();

    focusNode.addListener(() {
      setState(() {
        _hasFocus = focusNode.hasFocus;
      });
    });

    keyboardListener = KeyboardVisibilityController().onChange.listen((isShow) {
      if (!isShow) {
        loseFocus();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();

    focusNode.dispose();

    keyboardListener.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return SliverAppBar(
      backgroundColor: widget.primaryColor,
      automaticallyImplyLeading: false,
      pinned: true,
      title: Container(
        height: kToolbarHeight * 2 / 3,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            // 城市定位
            Consumer<LocationProvider>(
              builder: (BuildContext context, LocationProvider locationProvider,
                  Widget? child) {
                return GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    showCityListSelector<String>(
                      context: context,
                    ).then((String? city) {
                      if (city != null) {
                        locationProvider.setCity(city);
                      }
                    });
                  },
                  child: Row(
                    children: <Widget>[
                      Icon(
                        Icons.location_on,
                        color: Colors.white,
                        size: 20,
                      ),
                      Container(
                        width: 50,
                        child: Text(
                          locationProvider.city,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: 13,
                          ),
                        ),
                      ),
                    ],
                  ),
                );
              },
            ),
            // 搜索栏
            Expanded(
              flex: 1,
              child: Container(
                margin: EdgeInsets.only(left: 5),
                padding: EdgeInsets.symmetric(horizontal: 8),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius:
                      BorderRadius.all(Radius.circular(kToolbarHeight * 2 / 3)),
                ),
                child: TextField(
                  focusNode: focusNode,
                  cursorColor: Colors.black,
                  cursorWidth: 1,
                  textAlign: _hasFocus || _keyword.isNotEmpty
                      ? TextAlign.left
                      : TextAlign.center,
                  style: TextStyle(
                    fontSize: 15,
                    textBaseline: TextBaseline.alphabetic,
                  ),
                  decoration: InputDecoration(
                    hintText: '小区/写字楼/学校等',
                    border: InputBorder.none,
                    contentPadding: EdgeInsets.symmetric(
                      vertical: 8,
                      horizontal: 6,
                    ),
                    isDense: true,
                  ),
                  textInputAction: TextInputAction.search,
                  onChanged: (String value) {
                    setState(() {
                      _keyword = value;
                    });
                    widget.onChanged(value);
                  },
                  onSubmitted: (_) {
                    widget.onChanged(_keyword);
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
